const { queryTask, create, sort, delete: deleteTask, update, sortCross } = require("../service/task.service");

class TaskController {
  async getTaskDetail(ctx, next) {
    try {
      const { id } = ctx.request.params;
      const res = await queryTask({ id });
      ctx.success(res[0]);
    } catch (err) {
      ctx.fail("获取任务详情失败！")
    }
  }
  async getTaskList(ctx, next) {
    try {
      const { projectId, name, processorId, typeId } = ctx.request.body;
      let params = null;
      if (projectId || name || processorId || typeId) {
        params = {};
        projectId && (params.projectId = projectId);
        name && (params.name = name);
        processorId && (params.processorId = processorId);
        typeId && (params.typeId = typeId);
      }
      const res = await queryTask(params);
      ctx.success(res);
    } catch (err) {
      console.log(err)
      ctx.fail("获取任务列表失败！")
    }
  }
  async createTask(ctx, params) {
    try {
      const res = await create(ctx.state.taskForm);
      if (!!res.affectedRows) return ctx.success();
      ctx.fail("创建任务失败!");
    } catch (err) {
      ctx.fail("创建任务失败！")
    }
  }
  /**
   * @description: 排序接口
   * sortType:0 --- 当前看板移动
   * - 只需要传fromId,toId
   * sortType:1 --- 跨看板移动
   * - 插入某个看板的非末尾：fromId,toId
   * - 插入零一个看板的末尾：fromId,kanbanId(to)
   * 
   */  
  async sortTask(ctx, next) {
    const {sortType = 0 } = ctx.request.body;
    const params = ctx.state.sortForm;
    try {
      !sortType && sort([params[0],params[1]],sortType)
      !!sortType &&await sortCross(params);
      ctx.success();
    } catch (err) {
      console.log(err)
      ctx.fail("任务排序更新失败!");
    }
  }
  async deleteTaskById(ctx, next) {
    try {
      const res = await deleteTask(ctx.request.body)
      if (!!res.affectedRows) return ctx.success();
      ctx.fail("删除任务失败!")
    } catch (err) {
      ctx.fail("删除任务失败!");
    }
  }
  async updateTaskById(ctx, next) {
    let data = ctx.request.body;
    let params = [data, { id: data.id }];
    delete params[0].id;
    try {
      const res = await update(params);
      if (res.affectedRows > 0) return ctx.success();
      ctx.fail("更新任务失败!")
    } catch (err) {
      ctx.fail("更新任务失败!")
    }
  }
}
module.exports = new TaskController();